package cn.demo.um.support;

import cn.demo.um.domain.UmAttrData;
import cn.demo.um.service.IUmAttrDataService;
import cn.demo.um.support.drive.MatcherDrive;
import cn.demo.um.support.factory.MatcherDriveFactory;
import cn.demo.um.support.model.MatchScoreDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AttrMatchService implements IAttrMatchService {
    @Autowired
    private IUmAttrDataService umAttrDataService;
    @Autowired
    private MatcherDriveFactory matcherDriveFactory;

    @Override
    public List<MatchScoreDto> matchFullScoreDtoList(String userId, int start, int limit) {
        /*依据id构建执行驱动*/
        MatcherDrive matcherDrive= buildMatcherDriveById(userId);
        /*执行*/
        List<MatchScoreDto> matchScoreDtos = matcherDrive.invoke(start, limit);
        /*计算总分*/
        double v = matcherDrive.totalScore();
        matchScoreDtos.forEach(o -> o.setScore(o.getScore() / v * 100));
        return matchScoreDtos;
    }

    @Override
    public List<MatchScoreDto> matchSimpleScoreDtoList(String userId, int start, int limit) {
        /*依据id构建执行驱动*/
        MatcherDrive matcherDrive= buildMatcherDriveById(userId);
        /*执行*/
        List<MatchScoreDto> matchScoreDtos = matcherDrive.invoke(start, limit);
        return matchScoreDtos;
    }

    private MatcherDrive buildMatcherDriveById(String userId){
        /*构建条件*/
        List<UmAttrData> list = umAttrDataService.queryChain()
                .select()
                .from(UmAttrData.class)
                .eq(UmAttrData::getUserId, userId)
                .and(o -> {
                    o.eq(UmAttrData::getIsStandard, 1)
                            .or(UmAttrData::getAttrCode).eq(Constant.SEX_CODE);
                }).list();
        Map<String, UmAttrData> attrMap = list.stream().collect(Collectors.toMap(UmAttrData::getAttrCode, o -> o));
        String sex = attrMap.get(Constant.SEX_CODE).getAttrValue();
        attrMap.remove(Constant.SEX_CODE);

        if (Constant.MAN.equals(sex)) {
            sex = Constant.WOMAN;
        }else {
            sex=Constant.MAN;
        }
        /*构建执行驱动*/
        MatcherDrive matcherDrive = matcherDriveFactory.buildMatcherDrive(attrMap.values(), sex);
        return matcherDrive;
    }
}
